package com.common.fileuse;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * 通过url 将图片下载
 */
public class DlPicByUrl {
    //https://www.jitashe.org/tab/1337326/
    //https://att.jitashe.org/data/attachment/forum/201904/21/101641l2r95baaybs77aya.jpg!tab_thumb
    public static void main(String[] args) throws IOException {
        download("https://att.jitashe.org/data/attachment/forum/201904/21/101646apolbwb3qlo0bzo1.jpg!tab_thumb");
    }

    public static void download(String urlString) throws IOException {
        //构造URL
        URL url = new URL(urlString);
        URLConnection urlConnection = url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fou = new FileOutputStream("E:\\文件py\\吉他社谱子\\沉默是金\\2.jpg");

        byte[] bytes = new byte[1024];
        // 读取到的数据长度
        int read = inputStream.read(bytes);

        while (read != -1) {
            //write(byte[] b)方法： 将b.length个字节从指定字节数组写入此文件输出流中
            //write(byte[] b, int off, int len)方法：将指定字节数组中从偏移量off开始的len个字节写入此文件输出流
            //此处使用write(byte[] b, int off, int len) 为了保证不多读
            fou.write(bytes, 0, read);
            read = inputStream.read(bytes);
        }

        inputStream.close();
        fou.close();
    }
}
